package com.sxdz.web.account

import com.sxdz.api.webService.CalculatorDelegate
import com.sxdz.api.webService.CustomerVo
import com.sxdz.api.webService.UserCardCtmCardRltVo
import com.sxdz.api.webService.UserInfoVo
import com.sxdz.api.webService.UserPdtRltVo
import com.sxdz.constant.CommonConstant
import com.sxdz.constant.MessageConstant
import com.sxdz.controller.handler.CalculatorHandler
import com.sxdz.controller.service.account.IAccountService
import com.sxdz.controller.service.wechat.IWechatSubService
import com.sxdz.models.TCustomerVo
import com.sxdz.models.TWxAccount
import com.sxdz.models.TblWechatSubscribe
import com.sxdz.models.common.JsonResult
import com.toolbox.utils.DateUtil
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import me.chanjar.weixin.mp.api.WxMpService
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*

import javax.servlet.http.HttpServletRequest
/**
 * Created by LiYan on 2016/8/1.
 *
 * 账户信息接口
 */
@RestController
@CompileStatic
@TypeChecked
@RequestMapping("account")
class AccountAction {
    Logger logger = LoggerFactory.getLogger(this.getClass())
    @Autowired
    private IAccountService accountService
    @Autowired
    private IWechatSubService wechatSubService

    @Autowired
    private WxMpService wxMpService

    /**
     * 添加绑定账户
     * @param request
     * @return
     */
    @RequestMapping(value = "addAcc", method = RequestMethod.POST)
    @ResponseBody
     addAccount(HttpServletRequest request){
        def params=[:]
        params<<[openid:request.getParameter("openid") as String]
        TblWechatSubscribe tblWechatSubscribe=new TblWechatSubscribe()
        tblWechatSubscribe=wechatSubService.findObj(params) as TblWechatSubscribe
        if(null==tblWechatSubscribe){
            logger.info("未查询到对应用户信息")
            return new JsonResult<Object>(MessageConstant.FAIL_QUERY,null)
        }else{
            def intelligentNo=request.getParameter("intelligentNo") as String
            if(intelligentNo!=null && !"".equals(intelligentNo)){
                intelligentNo="0000000000000000".substring(0, 16-intelligentNo.length())+intelligentNo;
            }
            def param=[:]
            param<<[intelligentNo:intelligentNo]
            param<<[userId:tblWechatSubscribe.subcribeId];
            TWxAccount wxxAccount=accountService.findObj(param)
            if(null!=wxxAccount){
                logger.info("智能卡号已被绑定")
                return new JsonResult<Object>("1111"," 智能卡号已被绑定",wxxAccount.id)
            }else{
                TWxAccount tWxAccount=new TWxAccount()
                tWxAccount.setIntelligentNo(intelligentNo)
                tWxAccount.setRemarkName(request.getParameter("remarkName") as String)
                tWxAccount.setUserId((Long)tblWechatSubscribe.subcribeId)
                tWxAccount.setIsActive("0")
                def id=accountService.addBasic(tWxAccount)
                return new JsonResult<Object>(MessageConstant.SUCCESS.code.toString(),"",id)
            }

        }
    }

    /**
     * 获取智能卡号用户信息-用户客户核对自己信息
     * @param request
     */
    @RequestMapping(value = "checkAcc", method = RequestMethod.GET)
    @ResponseBody
    checkAccount(HttpServletRequest request,String intelligentNo){
        try{
            def params=[:]
            if(intelligentNo!=null && !"".equals(intelligentNo)){
                intelligentNo="0000000000000000".substring(0, 16-intelligentNo.length())+intelligentNo;
            }
            CalculatorDelegate calculatorDelegate= CalculatorHandler.getCalculatorPort();
            //获取客户编号
            List<UserCardCtmCardRltVo> userCardCtmCardRltVoList=calculatorDelegate.getUserCardCtmCardAll(intelligentNo);
            //查询客户信息
            List<CustomerVo> customerVoList;
            if(userCardCtmCardRltVoList!=null && userCardCtmCardRltVoList.size()>0){
                customerVoList=calculatorDelegate.getCustomerAll(userCardCtmCardRltVoList.get(0).ctmCard,intelligentNo);
            }
            if(customerVoList!=null && customerVoList.size()>0){
                CustomerVo customerVo=customerVoList.get(0) as CustomerVo;
                TCustomerVo tCustomerVo=new TCustomerVo();
                tCustomerVo.setIntelligentNo(intelligentNo);
                String cusName=customerVo.getCustomerName();
                if(cusName!=null && !"".equals(cusName)){
                    int len=cusName.length();
                    if(len>1){
                        String h1=cusName.substring(0,1);
                        String h2=cusName.substring(len-1);
                        if(len<2){}
                        else if(len>2){
                            String x="";
                            for(int i=0;i<len-2;i++){
                                x+="*";
                            }
                            cusName=h1+x+h2;
                        }else{
                            cusName="*"+h2;
                        }
                    }
                }
                tCustomerVo.setCustomerName(cusName);
                tCustomerVo.setmPhone(customerVo.getMPhone());
                tCustomerVo.setAddress(customerVo.getAddress());
                return new JsonResult<Object>(MessageConstant.SUCCESS,tCustomerVo)
            }else{
                return new JsonResult<Object>(MessageConstant.FAIL_QUERY,null)
            }
        }catch(Exception e){
        logger.error("获取客户信息异常！"+e.getStackTrace())
            return new JsonResult<Object>(MessageConstant.FAIL_QUERY,null)
        }

    }

    /**
     * 获取智能卡号用户产品信息及状态
     * @param request
     */
    @RequestMapping(value = "getBossAcc", method = RequestMethod.GET)
    @ResponseBody
    getBossAcc(HttpServletRequest request,String intelligentNo){
        try{
            def params=[:]
            if(intelligentNo!=null && !"".equals(intelligentNo)){
                intelligentNo="0000000000000000".substring(0, 16-intelligentNo.length())+intelligentNo;
            }
            CalculatorDelegate calculatorDelegate= CalculatorHandler.getCalculatorPort();
            //获取客户编号
            List<UserCardCtmCardRltVo> userCardCtmCardRltVoList=calculatorDelegate.getUserCardCtmCardAll(intelligentNo);
            //查询用户产品信息
            List<UserPdtRltVo> userPdtRltVoList=calculatorDelegate.getUserPdtRltInfo(userCardCtmCardRltVoList.get(0).ctmCard);
            //查询用户信息
            List<UserInfoVo> userInfoVoList=calculatorDelegate.getUserInfoAll(userCardCtmCardRltVoList.get(0).ctmCard);
            if(userInfoVoList!=null && userInfoVoList.size()>0){
                String status=userInfoVoList.get(0).status;//状态
                String yxDate="";
                if(userPdtRltVoList!=null && userPdtRltVoList.size()>0){
                    yxDate=DateUtil.formatDateTime2(userPdtRltVoList.get(0).BDate)+"-"+DateUtil.formatDateTime2(userPdtRltVoList.get(0).EDate);
                }
                return new JsonResult<Object>(MessageConstant.SUCCESS,[intelligentNo:intelligentNo,status:status,yxDate:yxDate] as Map)
            }else{
                return new JsonResult<Object>(MessageConstant.FAIL_QUERY,null)
            }
        }catch(Exception e){
            logger.error("获取智能卡用户信息异常！"+e.getStackTrace())
            return new JsonResult<Object>(MessageConstant.FAIL_QUERY,null)
        }

    }

    /**
     * 删除绑定账户
     * @param intelligentNo
     * @return
     */
    @RequestMapping(value = "delAcc", method = RequestMethod.POST)
    @ResponseBody
     delAccount(@RequestParam("id" )String id){
        String[] str=id.split(",")
        List<String> params = Arrays.asList(str);
        if(null!=params&&params.size()>0){
            for(def i=0;i<params.size();i++){
                //def param=[:]
               // param<<[id:params.get(i)]
                TWxAccount tWxAccount= accountService.findObjByKey(params.get(i) as Long) as TWxAccount;
                if(null!=tWxAccount){
                    logger.info("删除account id为"+params.get(i))
                    //accountService.delBasic(params)
                    accountService.deleteAcc(params.get(i) as Long)
                }
            }
            return new JsonResult<Object>(MessageConstant.SUCCESS,null)
        }else{
            logger.info("参数为空")
            return new JsonResult<Object>(MessageConstant.FAILURE,null)
        }
    }

    /**
     * 更新账户信息
     * @param tWxAccount
     * @return
     */
    @RequestMapping(value = "updateAcc", method = RequestMethod.POST)
    @ResponseBody
     updateAccount(@ModelAttribute("account")TWxAccount tWxAccount){
        accountService.modifyBasic(tWxAccount)
        return new JsonResult<Object>(MessageConstant.SUCCESS,null)
    }

    /**
     * 查询账户
     * @param openId
     * @return
     */
    @RequestMapping(value = "queryAcc/{openid}", method = RequestMethod.GET)
    @ResponseBody
     queryAccount(@PathVariable("openid")String openId){
        def params=[:]
        params<<[openid:openId]
        TblWechatSubscribe tblWechatSubscribe=wechatSubService.findObj(params) as TblWechatSubscribe
        if(null==tblWechatSubscribe){
            logger.info("未查询到绑定账户信息")
            return new JsonResult<Object>(MessageConstant.FAIL_QUERY,null)
        }else{
            def map=[:]
            map<<[userId:(Long)tblWechatSubscribe.subcribeId]
            List<TWxAccount> list=new ArrayList<TWxAccount>()
            list=accountService.findListByParams(map)
            return new JsonResult<Object>(MessageConstant.SUCCESS,list)
        }

    }

    /**
     * 根据授权返回的code 获取 openid
     * @param code
     * @return
     */
    @RequestMapping(value = "getOpenid/{code}", method = RequestMethod.GET)
    @ResponseBody
    getOpenIDByCode(@PathVariable("code") String code) {
        logger.info("=================code=" + code)
        String openid = ""
        try {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            openid = wxMpOAuth2AccessToken.openId
            logger.info("=================openId=" + openid)
            return new JsonResult<Object>(MessageConstant.SUCCESS,openid)
        } catch (Exception e) {
            logger.error("****************查询用户openId失败，错误信息： ",e);
            return new JsonResult<Object>(CommonConstant.ErrorMsg.E1002.value,CommonConstant.ErrorMsg.E1002.name,null)
        }
    }
}
